package cn.edu.xjtu.android.emoji_warfare_android;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import cn.edu.xjtu.android.emoji_warfare_android.game.Config;
import cn.edu.xjtu.android.emoji_warfare_android.game.Controller;
import cn.edu.xjtu.android.emoji_warfare_android.game.DataManager;
import cn.edu.xjtu.android.emoji_warfare_android.game.Engine;
import cn.edu.xjtu.android.emoji_warfare_android.util.Gap;
import cn.edu.xjtu.android.emoji_warfare_android.widget.GameFrameView;

/**
 * MainActivity<br>
 * 游戏主界面
 * 
 * @author bill
 *
 */
public class MainActivity extends Activity {
    /**
     * 图像绘制界面
     */
    GameFrameView frame;

    /**
     * 用于调试的文本框
     */
    TextView tvDebug;

    /**
     * 主角控制器
     */
    private Controller controller;

    /**
     * debug模式
     */
    private boolean debug = true;

    /**
     * 用于性能检查的Gap工具
     */
    Gap g;

    /**
     * 当前能否控制玩家
     */
    public boolean canControl = true;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化单例引用
        MainActivity.instance = this;
        // 设置View
        setView();
        // 设置监听器
        setListener();
        // 初始化游戏引擎
        initEngine();

        if (debug) {
            g = new Gap("Main");
            g.mstart();
        }

        if (debug) {
            tvDebug.setZ(100);
            openDebugThread();
        } else {
            tvDebug.setText("");
        }

    }

    private void initEngine() {
        if (getIntent().getBooleanExtra("newGame", false)) {
            // 创建引擎
            getApp().engine = new Engine(Config.screenWidth, Config.screenHeight, Config.margin);
            // 初始化生命数和模式
            getApp().engine.setLife(getIntent().getIntExtra("life", 0));
            getApp().engine.setMode(getIntent().getStringExtra("mode"));
            // 获取控制器
            controller = getEngine().getDefaultController();

            // 链接渲染引擎和图像绘制界面
            getEngine().Render.setCheckDraw(frame);
            frame.setOnDraw(getEngine().Render);
        }
    }

    // 生命周期控制

    @Override
    protected void onStart() {
        super.onStart();
        MainActivity.instance = this;
    }

    @Override
    protected void onResume() {
        super.onResume();
        getEngine().resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        getEngine().pause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        MainActivity.instance = null;
    }

    private void setView() {
        frame = (GameFrameView) findViewById(R.id.frame);
        tvDebug = (TextView) findViewById(R.id.textViewDebug);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void setListener() {
        frame.setOnTouchListener(new OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (!MainActivity.this.canControl) {
                    return true;
                }
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    controller.down(event.getX(), event.getY());
                    break;
                case MotionEvent.ACTION_UP:
                    controller.move(event.getX(), event.getY());
                    break;
                default:
                    controller.move(event.getX(), event.getY());
                    break;
                }
                return true;
            }
        });
    }

    private App getApp() {
        return (App) getApplication();
    }

    private Engine getEngine() {
        return getApp().engine;
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 游戏结束
            if (msg.what == 999) {
                // 获取游戏截图
                getEngine().stop();
                getApp().screenShot = getEngine().Render.getScreenShot();
                // 设置必要跳转信息
                long time = System.currentTimeMillis();
                Intent t = new Intent(MainActivity.this, EndActivity.class);
                t.putExtra("waveIndex", Engine.instance.el.waveIndex);
                t.putExtra("time", time);
                // 保存得分
                DataManager dm = new DataManager(MainActivity.this);
                dm.save(Engine.instance.sb.score, getIntent().getStringExtra("mode"), time);
                // 启动跳转
                startActivity(t);
                finish();
            }
        }
    };

    private void openDebugThread() {
        // 启动Debug用线程
        new Thread() {
            @Override
            public void run() {
                for (;;) {
                    try {
                        // 每隔30ms刷新一次重要的游戏内核信息
                        Thread.sleep(30);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                StringBuilder sb = new StringBuilder();
                                sb.append("Move:");
                                sb.append(getEngine().Move.isRunning());
                                sb.append(" Render:");
                                sb.append(getEngine().Render.isRunning());
                                sb.append(" Delayed:");
                                sb.append(getEngine().Delayed.isRunning());
                                sb.append(" Collide:");
                                sb.append(getEngine().Collide.isRunning());
                                sb.append(" \nPlayerBullet: ");
                                sb.append(getEngine().Layers.PlayerBullet.size());
                                sb.append(" EnemyBullet: ");
                                sb.append(getEngine().Layers.EnemyBullet.size());
                                sb.append(" GameClock: ");
                                sb.append(getEngine().clock());
                                sb.append("\nItemCount: ");
                                sb.append(getEngine().Layers.Item.size());
                                sb.append(" HasLaser: ");
                                sb.append(getEngine().hasLaser);
                                sb.append(getEngine().Move.getError());
                                sb.append(getEngine().Render.getError());
                                sb.append(getEngine().Delayed.getError());
                                sb.append(getEngine().Collide.getError());
                                tvDebug.setText(sb.toString());
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        }.start();
    }

    /**
     * 单例引用
     */
    public static MainActivity instance;
}
